<template>
  <div class="cart-page container">
    <CartSection
      :is-logged-in="isLoggedIn"
      :items="items"
      :loading="cartLoading"
      :error="cartError"
      :total-qty="totalQty"
      :total-amount="totalAmount"
      @login="openLogin"
      @refresh="loadCart"
      @update="handleUpdate"
      @remove="handleRemove"
      @verify="handleVerify"
    />
  </div>
</template>

<script setup>
import { computed, inject, onMounted, watch } from "vue";
import { useRouter } from "vue-router";
import CartSection from "../components/CartSection.vue";
import { useCartStore } from "../store/cart";
import { useUserStore } from "../store/user";
import { useVerificationStore } from "../store/verification";
import { message } from "../utils/message";

const cartStore = useCartStore();
const userStore = useUserStore();
const verificationStore = useVerificationStore();
const router = useRouter();
const appBridge = inject("appBridge", null);

const isLoggedIn = computed(() => userStore.isLoggedIn);
const items = computed(() => cartStore.items);
const cartLoading = computed(() => cartStore.loading);
const cartError = computed(() => cartStore.error);
const totalQty = computed(() => cartStore.totalQty);
const totalAmount = computed(() => cartStore.amountSummary);

const openLogin = () => {
  appBridge?.openLogin?.();
};

const loadCart = async () => {
  if (!isLoggedIn.value) {
    cartStore.clear();
    return;
  }
  try {
    await cartStore.load();
  } catch (error) {
    message.error(error.message || "购物车加载失败");
  }
};

const handleUpdate = async ({ id, qty }) => {
  try {
    await cartStore.updateQty(id, qty);
    message.success("数量已更新");
  } catch (error) {
    message.error(error.message || "更新失败");
    loadCart();
  }
};

const handleRemove = async item => {
  if (!window.confirm(`确定删除「${item.name}」吗？`)) return;
  try {
    await cartStore.remove(item.id);
    message.success("已从购物车移除");
  } catch (error) {
    message.error(error.message || "删除失败");
    loadCart();
  }
};

const handleVerify = async item => {
  try {
    await verificationStore.create(item.id, {
      buyer_qty: item.qty,
      buyer_remark: `确认型号 ${item.model}`
    });
    message.success("核实请求已提交，可前往核实记录查看进度");
    router.push({ name: "verification" });
  } catch (error) {
    message.error(error.message || "发起核实失败");
  }
};

onMounted(() => {
  loadCart();
});

watch(isLoggedIn, () => {
  loadCart();
});
</script>

<style scoped lang="scss">
.cart-page {
  padding-top: 32px;
  padding-bottom: 48px;
}
</style>
